package com.derbysoft.lowcostadapter.dswitch3.handler.impl;

import com.derbysoft.dswitch.dto.common.KeyValue;
import com.derbysoft.dswitch.remote.hotel.dto.HotelCancelRequest;
import com.derbysoft.dswitch.remote.hotel.dto.HotelCancelResponse;
import com.derbysoft.lowcostadapter.commons.log.TransactionLogger;
import com.derbysoft.lowcostadapter.commons.model.OperationType;
import com.derbysoft.lowcostadapter.commons.model.ReservationLog;
import com.derbysoft.lowcostadapter.dswitch2.service.helper.Constant;
import com.derbysoft.lowcostadapter.dswitch3.handler.RemoteServiceHandler;
import com.derbysoft.lowcostadapter.dswitch3.service.HotelProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

/**
 * Created by: jason
 * Date: 2012-06-28
 */
@Service("hotelCancelHandler")
public class HotelCancelHandler extends AbstractDSwitch3Handler<HotelCancelRequest, HotelCancelResponse>
        implements RemoteServiceHandler<HotelCancelRequest, HotelCancelResponse> {

    @Autowired
    @Qualifier("ds3HotelCancelService")
    protected HotelProviderService<HotelCancelRequest, HotelCancelResponse> hotelProviderService;

    @Override
    public HotelCancelResponse handle(HotelCancelRequest request) {
        TransactionLogger.getReservationLogger().set(createCancellationLog(request));

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        HotelCancelResponse response = hotelProviderService.execute(request);

        stopWatch.stop();

        long elapsedTime = stopWatch.getTotalTimeMillis();
        response.getElapsedTimes().add(new KeyValue(ElapsedTimeType.LCB_ADAPTER.name(), String.valueOf(elapsedTime)));
        TransactionLogger.getReservationLogger().get().setTimeSpan(elapsedTime);

        if (Boolean.valueOf(loadSystemVariable(Constant.APPEND_DERBY_LOG).getValue())) {
            appendLogDetail(request, response);
        }
        return response;
    }

    private ReservationLog createCancellationLog(HotelCancelRequest request) {
        ReservationLog reservationLog = new ReservationLog();
        reservationLog.setTaskId(request.getHeader().getTaskId());
        reservationLog.setChannel(request.getHeader().getSource());
        reservationLog.setErsp(request.getHotelCancelRQ().getErsp());
        reservationLog.setOperationType(OperationType.CANCELLATION);
        return reservationLog;
    }
}
